package com.heima.admin.gateway.filter;

import com.heima.common.dtos.Payload;
import com.heima.common.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    /**
     * 过滤业务
     * 登录验证
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
//         获取请求路径
        String path = request.getURI().getPath();
        log.info("请求路径path={}",path);
//        判断请求是否登录请求
        if(path.contains("/login/in")){
//        如果是，放行
            return chain.filter(exchange);
        }
//        不是登录请求，获取token
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isBlank(token)) {
//        如果没有token，返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try{
//        验证token
            Payload payload = JwtUtils.getInfoFromToken(token);
//            获取userId
            Integer userId = payload.getUserId();
            log.info("userId=={}",userId);
//            放入请求头中
            ServerHttpRequest httpRequest = request.mutate()
                    .headers(httpHeaders -> {
                        httpHeaders.set("userId", userId.toString());
                    })
                    .build();
            String userId1 = httpRequest.getHeaders().getFirst("userId");
            log.info("userId1=={}",userId1);
            exchange.mutate().request(httpRequest);
//        验证成功放行
            return chain.filter(exchange);
        }catch (Exception e){
            //        验证不成功，返回401
            log.error("token验证失败！");
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


    }

    @Override
    public int getOrder() {
        return 0;
    }
}
